import React, {useState, useEffect} from 'react';
import {useParams, Link} from 'react-router-dom';
import {
    Box,
    Typography,
    CircularProgress,
    Card,
    CardContent,
    Breadcrumbs,
    Divider, CardActions,
    Button,
} from '@mui/material';
import {
    AccessTime as TimeIcon,
    Folder as CategoryIcon,
    Visibility as ReadIcon,
    ArrowBackIosNew,
    ArrowForwardIos
} from '@mui/icons-material';
import {queryArticleDetail, ArticleDetail} from '@services/front/article';
import {useTheme} from "@mui/material/styles";
import {format} from 'date-fns';
import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined";

const ArticleDetails: React.FC = () => {
    const theme = useTheme();
    const {articleId} = useParams<{ articleId: string }>();
    const [article, setArticle] = useState<ArticleDetail | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchArticle = async () => {
            if (!articleId) {
                setError('Article ID is missing.');
                setLoading(false);
                return;
            }
            try {
                setLoading(true);
                const data = await queryArticleDetail(Number(articleId));
                setArticle(data);
            } catch (err) {
                console.error('Error fetching article details:', err);
                setError('Failed to load article details.');
            } finally {
                setLoading(false);
            }
        };

        fetchArticle();
    }, [articleId]);

    // 移除HTML标签的函数
    const stripHtmlTags = (html: string) => {
        return html.replace(/<[^>]*>?/gm, '');
    };

    if (loading) {
        return (
            <Box sx={{display: 'flex', justifyContent: 'center', mt: 10}}>
                <CircularProgress/>
            </Box>
        );
    }

    if (error) {
        return (
            <Typography color="error" align="center" sx={{mt: 10}}>
                {error}
            </Typography>
        );
    }

    if (!article) {
        return (
            <Typography align="center" sx={{mt: 10}}>
                Article not found.
            </Typography>
        );
    }

    return (
        <Box sx={{
            flex: 3.5,
            display: 'grid',
            gridTemplateColumns: {xs: '1fr'},
            gap: 0.2,
            bgcolor: theme.palette.background.default,
            color: theme.palette.text.primary,
            transition: 'background 0.3s, color 0.3s',
        }}>
            {/* 面包屑导航 */}
            <Breadcrumbs aria-label="breadcrumb" sx={{
                mb: 3,
                bgcolor: theme.palette.background.default,
                color: theme.palette.text.primary,
                transition: 'background 0.3s, color 0.3s',
            }}>
                <Link to="/dashboard/articles" style={{textDecoration: 'none', color: 'inherit'}}>
                    文章
                </Link>
                <Typography color="text.primary">{article.title}</Typography>
            </Breadcrumbs>
            {/* 文章内容卡片 */}
            <Card elevation={4} sx={{
                bgcolor: theme.palette.background.paper,
                color: theme.palette.text.primary,
                transition: 'box-shadow 0.3s, background 0.3s, color 0.3s',
                boxShadow: theme.palette.mode === 'light'
                    ? '8px 12px 32px -8px rgba(80,80,80,0.13)'
                    : '8px 12px 32px -8px rgba(0,0,0,0.36)',
                '&:hover': {
                    boxShadow: theme.palette.mode === 'light'
                        ? '16px 24px 48px -8px rgba(80,80,80,0.22)'
                        : '16px 24px 48px -8px rgba(0,0,0,0.48)'
                }
            }}>
                <CardContent>
                    {/* 标题 */}
                    <Typography variant="h4" component="h1" gutterBottom sx={{fontWeight: 600}}>
                        {article.title}
                    </Typography>

                    {/* 副标题信息 */}
                    <Box sx={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: 2,
                        mb: 1.5,
                        color: 'text.secondary'
                    }}>
                        <Box sx={{display: 'flex', alignItems: 'center'}}>
                            <TimeIcon fontSize="small" color='primary' sx={{mr: 0.5}}/>
                            <Typography variant="body2">
                                {format(new Date(article.updateTime), 'yyyy年MM月dd日')}
                            </Typography>
                        </Box>

                        <Box sx={{display: 'flex', alignItems: 'center'}}>
                            <FolderOutlinedIcon fontSize="small" sx={{color: '#FFD700', mr: 0.5}}/>
                            <Typography variant="body2">
                                {article.categoryName}
                            </Typography>
                        </Box>

                        <Box sx={{display: 'flex', alignItems: 'center'}}>
                            <ReadIcon fontSize="small" sx={{color: '#4CAF50', mr: 0.5}}/>
                            <Typography variant="body2">
                                {article.readNum} 阅读
                            </Typography>
                        </Box>
                    </Box>

                    <Divider sx={{my: 2}}/>

                    {/* 文章内容 */}
                    <Typography variant="body1" component="div" sx={{
                        lineHeight: 1.8,
                        '& p': {
                            mb: 2
                        }
                    }}>
                        {stripHtmlTags(article.content)}
                    </Typography>
                </CardContent>
                <CardActions sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-end',
                    px: 2,
                    pb: 2,
                    pt: 0
                }}>
                    {/* 上一篇按钮 */}
                    {article.preArticle && article.preArticle.title && (
                        <Button
                            variant="outlined"
                            color="primary"
                            sx={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'flex-start',
                                minWidth: 120,
                                p: 1,
                                textAlign: 'left',
                            }}
                            component={article.preArticle.id ? Link : 'button'}
                            to={`/dashboard/articles/${article.preArticle.id}`}
                        >
                            <Box sx={{display: 'flex', alignItems: 'center', mb: 0.5}}>
                                <ArrowBackIosNew fontSize="small" sx={{mr: 0.5}}/>
                                <Typography variant="body2" sx={{fontWeight: 500}}>上一篇</Typography>
                            </Box>
                            <Box sx={{
                                display: 'flex',
                                alignItems: 'right',
                                justifyContent: 'flex-end'
                            }}>
                                <Typography variant="button" sx={{
                                    color: 'text.secondary',
                                    whiteSpace: 'nowrap',
                                    maxWidth: 140,
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis'
                                }}>
                                    {article.preArticle.title}
                                </Typography>
                            </Box>
                        </Button>
                    )}
                    <Box sx={{flex: 1}}/>
                    {/* 下一篇按钮 */}
                    {article.nextArticle && article.nextArticle.title && (
                        <Button
                            variant="outlined"
                            color="primary"
                            sx={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'flex-end',
                                minWidth: 120,
                                p: 1,
                                textAlign: 'right',
                            }}
                            component={article.nextArticle.id ? Link : 'button'}
                            to={`/dashboard/articles/${article.nextArticle.id}`}
                        >
                            <Box sx={{display: 'flex', alignItems: 'center', justifyContent: 'flex-end', mb: 0.5}}>
                                <Typography variant="body2" sx={{fontWeight: 500}}>下一篇</Typography>
                                <ArrowForwardIos fontSize="small" sx={{ml: 0.5}}/>
                            </Box>
                            <Typography variant="button" sx={{
                                color: 'text.secondary',
                                whiteSpace: 'nowrap',
                                // maxWidth: 140,
                                // overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                textAlign: 'left'
                            }}>
                                {article.nextArticle.title}
                            </Typography>
                        </Button>
                    )}
                </CardActions>
            </Card>
        </Box>
    );
};

export default ArticleDetails;
